package com.six.service;

import com.six.mapper.CategoryMapper;
import com.six.domain.entity.Category;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
@Service
@RequiredArgsConstructor
public class CategoryService {
    private final CategoryMapper categoryMapper;

    @CacheEvict(value = "menu", key = "#storeId")
    public void save(String name, Integer storeId) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("分类名称不能为空");
        }

        // 检查该店铺下是否已存在同名分类
        boolean exists = listByStore(storeId)
                .stream()
                .anyMatch(c -> c.getName().equalsIgnoreCase(name.trim()));
        if (exists) {
            throw new IllegalArgumentException("该分类名称已存在");
        }
        Category category = new Category();
        category.setStoreId(storeId.longValue());
        category.setName(name.trim());
        category.setSortOrder(0); // 默认排序值，可按需调整

        categoryMapper.insert(category);
    }

    public List<Category> listByStore(Integer storeId) {
        return categoryMapper.listByStore(storeId);
    }

    @CacheEvict(value = "menu", key = "#storeId")
    public void deleteCategoryById(Integer storeId, List<Long> ids) {
        if (storeId == null || ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("storeId 或 ids 不能为空");
        }
        categoryMapper.deleteCategoryById(storeId, ids);
    }
}